import 'package:flutter/material.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/dialog/dialog_utils.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/mine/user_follower_list.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/mine_followers_viewmodel.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';

class MineFollowerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MineFollowerViewModel>(
        create: (_) {
          var model = MineFollowerViewModel();
          model.loadData();
          return model;
        },
        child: Scaffold(
          appBar: PreferredSize(
            preferredSize: Size(double.infinity, 95.h),
            child: Container(
              color: Theme.of(context).backgroundColor,
              child: SafeArea(
                  child: Row(
                children: <Widget>[
                  MySubassembly.getBackIcon(context,
                      color: Theme.of(context).textTheme.subtitle2.color),
                  Expanded(
                    child: Center(
                      child: Text(
                        StringResources.wo_de_guan_zhu,
                        style: TextStyle(
                            fontSize: 32.sp,
                            fontWeight: FontWeight.w500,
                            color: Theme.of(context).textTheme.subtitle2.color),
                      ),
                    ),
                  ),
                  MySubassembly.getSearchIcon(null, text: Text('')),
                  Container(
                    height: 10.h,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('images/colorBar.png'), fit: BoxFit.cover)),
                  )
                ],
              )),
            ),
          ),
          body: Selector<MineFollowerViewModel, BaseState>(
              builder: (context, state, _) {
                if (state == BaseState.FAIL) {
                  return FailWidget();
                }
                if (state == BaseState.LOADING) {
                  return LoadingWidget();
                }
                if (state == BaseState.CONTENT || state == BaseState.EMPTY) {
                  PagewiseLoadController pageLoadController = PagewiseLoadController<Follower>(
                      pageFuture: (page) =>
                          Provider.of<MineFollowerViewModel>(context, listen: false).nextData(page),
                      pageSize: 6);
                  return Container(
                    decoration: BoxDecoration(
                      border: Border(top: BorderSide(width: 1.h, color: Color(0xFFEBECF1))),
                      color: Theme.of(context).backgroundColor,
                    ),
                    child: MediaQuery.removePadding(
                      context: context,
                      child: RefreshIndicator(
                        onRefresh: () async {
                          Provider.of<MineFollowerViewModel>(context, listen: false).refresh();
                          pageLoadController.reset();
                        },
                        child: PagewiseListView<Follower>(
                            pageLoadController: pageLoadController,
                            loadingBuilder: (_) => MySubassembly.getLoadingItem(),
                            noItemsFoundBuilder: (_) => MySubassembly.getNullItem(msg: '无更多关注'),
                            itemBuilder: (context, item, index) {
                              return Container(
                                margin: const EdgeInsets.only(left: 30.5),
                                padding: const EdgeInsets.only(top: 25, bottom: 20),
                                decoration: BoxDecoration(
                                    color: Color(0xFFFFFFFF),
                                    border: Border(
                                        top: BorderSide(color: Color(0xFFEBECF1), width: 0.5))),
                                child: Row(
                                  mainAxisSize: MainAxisSize.max,
                                  children: <Widget>[
                                    GestureDetector(
                                      onTap: () {
                                        Navigator.of(context).pushNamed(Routes.mine_user_info,
                                            arguments: item.user.userId.toString());
                                      },
                                      child: CircleAvatar(
                                        radius: 30,
                                        backgroundImage: NetworkImage(item.user.portrait),
                                      ),
                                    ),
                                    const SizedBox(width: 15),
                                    Expanded(
                                      child: _renderContent(item.user.nickname, item.user.desc),
                                    ),
                                    _renderFollowBtn(
                                        context: context,
                                        isMutualFollowing: item.mutual_following,
                                        entity: item,
                                        pageLoadController: pageLoadController),
                                  ],
                                ),
                              );
                            }),
                      ),
                    ),
                  );
                }
                return Constants.empty;
              },
              selector: (_, model) => model.mState),
        ));
  }

  _renderFollowBtn(
      {BuildContext context,
      int isMutualFollowing = 0,
      Follower entity,
      PagewiseLoadController pageLoadController}) {
    return GestureDetector(
      onTap: () async {
        var delete = await showSelectorDialog(context, entity.user.nickname);
        if (delete != null) {
          context.read<MineFollowerViewModel>().cancelFollow(entity, pageLoadController.loadedItems,
              onSuccess: () {
                pageLoadController.retry();
              },
              onError: (str) => Toast.show(str, context));
        }
      },
      child: Container(
        margin: const EdgeInsets.only(right: 30.5),
        padding: const EdgeInsets.fromLTRB(7.5, 4, 7.5, 4),
        decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.all(Radius.circular(2.5)),
            border: Border.all(width: 0.5, color: Color(0xFF82868E))),
        child: Row(
          children: <Widget>[
            Image.asset(
                isMutualFollowing == 0 ? 'images/mine_follow.png' : 'images/mine_follow_2.png',
                width: 15),
            Text(isMutualFollowing == 0 ? '已关注' : '互相关注',
                style: TextStyle(
                    color: Color(0xFF82868E), fontWeight: FontWeight.w500, fontSize: 12, height: 1))
          ],
        ),
      ),
    );
  }

  _renderContent(String name, String desc) {
    return Column(
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(name,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: Color(0xFF000000), fontWeight: FontWeight.w600, fontSize: 16, height: 1)),
        desc != null
            ? Text(desc,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: Color(0xFF999999),
                    fontWeight: FontWeight.w500,
                    fontSize: 11,
                    height: 1.6))
            : SizedBox.shrink()
      ],
    );
  }

  Future showSelectorDialog(BuildContext context, String name) async {
    return await showDialog(
        context: context,
        builder: (context) {
          return DialogUtil.showMessageDialog(context, '取消关注', '是否不在关注 $name?');
        });
  }

  _renderContainer(
      {String text,
      Color bgc = Colors.white,
      bool hasBorder = false,
      Color textColor = const Color(0xFF000000),
      double fontSize = 16}) {
    return Container(
      height: 63,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: bgc,
          border:
              Border(bottom: BorderSide(color: Color(0xFFF6F6F7), width: hasBorder ? 0.5 : 0.0))),
      child: Text(text,
          style: TextStyle(
              color: textColor, fontWeight: FontWeight.w500, fontSize: fontSize, height: 1)),
    );
  }
}
